from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import date, datetime as dt, timedelta
import datetime
from google.appengine.api import users
from google.appengine.ext import db
from models.ChiTietDonHang import ChiTietDonHang
from models.DonHang import DonHang
from models.HangHoa import HangHoa
from models.KhachHang import KhachHang
from models.NhanVien import NhanVien
from utils.Const import TrangThaiDonHang, TrangThaiGiaBan
from utils.permission_required import permission_required
import WSGI
import json as simplejson
import logging
import math
import webapp2

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiDonHang(webapp2.RequestHandler):
    priv = ''
    perm = 'KinhDoanh.DatHang'
    @permission_required
    def get(self):
        nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstKhachHang = DaoQuanLyNhanVien.getAllKhachHang(nhanVien.key().id())
        
        for item in lstKhachHang:
            item['tenKhachHang'] = str(item['id']) + ' - ' + item['tenKhachHang']
        lstDonHang = []
         
        
        lstHangHoa = DaoQuanLyNhanVien.getAllHangHoa()
        
        lstHangHoaText = ''
        
        for item in lstHangHoa:
#            item['tenHangHoa'] = str(item['id']) + ' - ' + item['tenHangHoa']
            lstHangHoaText += str(item['id']) + ':' + item['tenHangHoa'] + ';'
        lstHangHoaText = lstHangHoaText[:-1] 
        
        maDonHang = self.request.get('id')
        ngayGiao = ''
        ngayThanhToan = ''
        maKhachHang = ''
        ghiChu = ''
        maTrangThai= 0
        if maDonHang == '':
            if lstKhachHang.__len__() > 0:
                query = DonHang.all()
                query.filter('maKH =', lstKhachHang[0]['id'])
                items = query.fetch(1, 0)
                for item in items:
                    lstDonHang.append(item.key().id())
            donHang = DonHang()
            donHang.trangThai = TrangThaiDonHang.DANG_DAT_HANG
            donHang.ngayDat = date.today()
            donHang.tienDaThanhToan = 0.0
            donHang.maNVDat = nhanVien.key().id()
            donHang.tenNVDat = nhanVien.tenNV
            donHang.tongTien = 0.0
            donHang.put()
            maDonHang = donHang.key().id()
            ngayDat = date.today().strftime('%d/%m/%Y')
            ngayGiao = (date.today()+timedelta(days=1)).strftime('%d/%m/%Y 00:00')
            ngayThanhToan = (date.today()+timedelta(days=1)).strftime('%d/%m/%Y')
        else:
            donHang = DaoQuanLyNhanVien.getDonHangById(int(maDonHang))
            
            query = DonHang.all()
            query.filter('maKH =', donHang.maKH)
            items = query.fetch(1, 0)
            for item in items:
                lstDonHang.append(item.key().id())
            ngayDat = donHang.ngayDat
            try:
                ngayGiao = donHang.ngayGiao.strftime('%d/%m/%Y %H:%M')
            except:
                pass
            try:
                ngayThanhToan = donHang.ngayThanhToan.strftime('%d/%m/%Y')
            except:
                pass
            try:
                kh = DaoQuanLyNhanVien.getKhachHangById(donHang.maKH)
                lstKhachHang.append({'id':kh.key().id(), 'tenKhachHang':str(kh.key().id()) + ' - ' + kh.tenKhachHang})
                if kh.maNV != nhanVien.key().id() and self.priv != 'Manager' and self.priv != 'Owner' and NhanVien.get_by_id(kh.maNV).parentId != nhanVien.key().id():
                    template = WSGI.jinja_environment.get_template('/html/DatHang.html')
                    self.response.out.write(template.render({}))
                maKhachHang = kh.key().id()
            except:
                pass
            ghiChu = donHang.ghiChu
            maTrangThai = donHang.trangThai
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nhanVien.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'priv': self.priv,
                        'lstKhachHang': lstKhachHang,
                        'lstHangHoaText': lstHangHoaText,
                        'maDonHang': maDonHang,
                        'ngayDat': ngayDat,
                        'ngayGiao':ngayGiao,
                        'ngayThanhToan':ngayThanhToan,
                        'maKhachHang':maKhachHang,
                        'ghiChu':ghiChu,
                        'maTrangThai': maTrangThai,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri),
                        'lstDonHang': lstDonHang,
                        'maNV': nhanVien.key().id(),
                        'duTru': donHang.duTru
        }

        template = WSGI.jinja_environment.get_template('/html/DatHang.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'KinhDoanh.DatHang'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListChiTietDonHang': 'getListChiTietDonHang',
                       'updateChiTietDonHang': 'updateChiTietDonHang',
                       'updateDonHang': 'updateDonHang',
                       'deleteDonHang': 'deleteDonHang',
                       'getListDonHangMau': 'getListDonHangMau',
                       'donHangMau': 'donHangMau',
                       'getIdDonHangDuTru': 'getIdDonHangDuTru'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListChiTietDonHang(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maDonHang = self.request.get('maDonHang')
        rows, rowNum = DaoQuanLyNhanVien.getListChiTietDonHang(maDonHang, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateChiTietDonHang(self):
        maChiTietDonHang = self.request.get('id')
        if maChiTietDonHang != '_empty':
            ctdh = ChiTietDonHang.get_by_id(int(maChiTietDonHang))
        else:
            ctdh = ChiTietDonHang()
        oper = self.request.get('oper')
        maDonHang = ctdh.maDonHang
        if maDonHang is not None:
            dh = DaoQuanLyNhanVien.getDonHangById(maDonHang)
        logger.debug(oper)
        if oper == 'del':
            if maDonHang != None and (dh.trangThai == TrangThaiDonHang.DANG_DAT_HANG or dh.trangThai == TrangThaiDonHang.DA_DAT_HANG or self.priv == 'Owner'):
                ck = KhachHang.get_by_id(dh.maKH)
                if ck is None:
                    ck = 0.0;
                else: 
                    ck = ck.chietKhau
                if ck is None:
                    ck = 0.0
                dh.tongTien -= ctdh.thanhTien * (1 - ck/100) 
                dh.put()
                DaoQuanLyNhanVien.deleteChiTietDonHang(ctdh)
            return 1
        else:
            maHang = int(self.request.get('hangHoa'))
            try:
                soLuong = float(self.request.get('soLuong'))
            except:
                soLuong = 0.0
            try:
                duTru = float(self.request.get('duTru'))
            except:
                duTru = 0.0
            ghiChu = self.request.get('ghiChu')
            maKhachHang = int(self.request.get('maKhachHang'))
            donGia = DaoQuanLyNhanVien.getGiaBan(maKhachHang, maHang)
            thanhTien = donGia * soLuong
            ctdh.donGia = donGia
            ctdh.thanhTien = thanhTien
            ctdh.maDonHang = int(self.request.get('maDonHang'))
            ctdh.maHang = maHang
            ctdh.tenHang = DaoQuanLyNhanVien.getHangHoaById(maHang).tenHangHoa
            ctdh.soLuong = soLuong
            ctdh.duTru = duTru
            ctdh.ghiChu = ghiChu
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
            ctdh.nvThayDoi = str(nhanVien.key().id()) + ' - ' + nhanVien.tenNV
            dh = DaoQuanLyNhanVien.getDonHangById(ctdh.maDonHang)
            
            items = []
            
            if self.priv == 'Manager':
                ctdh.trangThai = TrangThaiGiaBan.CHUA_DUYET
            elif self.priv == 'Owner':
                if self.request.get('trangThai').strip() == TrangThaiGiaBan.DUYET:
                    ctdh.trangThai = self.request.get('trangThai').strip()
                    if dh.trangThai != TrangThaiDonHang.DA_DAT_HANG and dh.trangThai != TrangThaiDonHang.DANG_DAT_HANG:
                        hh = HangHoa.get_by_id(ctdh.maHang)
                        hh.soLuongTonKho -= ctdh.soLuong
                        if hh.soLuongTonKho < 0:
                            hh.soLuongTonKho = 0
                        items.append(hh)
            elif self.priv == 'Staff':
                ctdh.trangThai = TrangThaiGiaBan.DUYET
            
            if maChiTietDonHang != '_empty':
                ctdh.trangThai = TrangThaiGiaBan.DUYET
            
            
            if ctdh.trangThai == TrangThaiGiaBan.DUYET:
                dh = DonHang.get_by_id(ctdh.maDonHang)
                ck = KhachHang.get_by_id(maKhachHang)
                if ck is None:
                    ck = 0.0;
                else: 
                    ck = ck.chietKhau
                if ck is None:
                    ck = 0.0
                if dh.tongTien is None:
                    dh.tongTien = 0.0
                dh.tongTien += ctdh.thanhTien * (1 - ck/100)
                items.append(dh)
                if dh.trangThai == TrangThaiDonHang.DA_GIAO_HANG:
                    dthu = DaoQuanLyNhanVien.getDoanhThuByMaKhachHangAndNgay(dh.maKH, (dt.now() + datetime.timedelta(hours=7)).date())
                    dthu.doanhThu += ctdh.thanhTien* (1 - ck/100)
                    items.append(dthu)
                    kh = KhachHang.get_by_id(dh.maKH)
                    kh.congNo += ctdh.thanhTien* (1 - ck/100)
                    items.append(kh)
                db.put(items)
                
            
            DaoQuanLyNhanVien.createOrUpdateChiTietDonHang(ctdh)
            return 1

    def updateDonHang(self):
        try:
            maDonHang = int(self.request.get('maDonHang'))
            dh = DaoQuanLyNhanVien.getDonHangById(maDonHang)
            dh.ngayDat = (dt.now() + datetime.timedelta(hours=7)).date()
            dh.ngayGiao = dt.strptime(self.request.get('ngayGiao'), '%d/%m/%Y %H:%M')
            dh.ngayGiao1 = dt.strptime(self.request.get('ngayGiao'), '%d/%m/%Y %H:%M').date()
            dh.maKH = int(self.request.get('maKhachHang'))
            dh.ngayThanhToan = dt.strptime(self.request.get('ngayThanhToan'), '%d/%m/%Y').date()
            if dh.maKH != dh.maNVDat:
                kh = KhachHang.get_by_id(dh.maKH)
                if kh.hanThanhToan is None or kh.hanThanhToan < dh.ngayThanhToan:
                    kh.hanThanhToan = dh.ngayThanhToan
                if dh.maNVGiaoHang is None:
                    dh.maNVGiaoHang = kh.maNVGiaoHang
                    dh.tenNVGiaoHang = kh.tenNVGiaoHang
            
            #dh.trangThai = self.request.get('trangThai')
            if dh.trangThai == TrangThaiDonHang.DANG_DAT_HANG:
                dh.trangThai = TrangThaiDonHang.DA_DAT_HANG
            dh.ghiChu = self.request.get('ghiChu')
            DaoQuanLyNhanVien.createOrUpdateDonHang(dh)
            return 1
        except Exception, ex:
            return ex.__str__()
    
    def deleteDonHang(self):
        try:
            maDonHang = int(self.request.get('maDonHang'))
            DaoQuanLyNhanVien.deleteDonHang(maDonHang)
            return 1
        except Exception, ex:
            return ex.__str__()
        
    def getListDonHangMau(self):
        maKH = self.request.get('maKH')
       
        queryRemoveFailedDonHang = DonHang.all().filter('trangThai =', TrangThaiDonHang.DANG_DAT_HANG)
        queryRemoveFailedDonHang.filter('maKH =', int(maKH))
        lstFailedDonHang = []
        for item in queryRemoveFailedDonHang:
            lstFailedDonHang.append(item)
        db.delete(lstFailedDonHang)
        
        query = DonHang.all()
        query.filter('maKH =', int(maKH))
        
        query.order('-__key__')
        items = query.fetch(1, 0)
        lstDonHang = []
        for item in items:
            lstDonHang.append(item.key().id())
        return simplejson.dumps(lstDonHang);
    
    def getIdDonHangDuTru(self):
        maNV = int(self.request.get('maNV'))
        query = DonHang.all()
        query.filter('maNVDat', int(maNV))
        query.filter('maKH', int(maNV))
        query.filter('ngayDat', (dt.now() + datetime.timedelta(hours=7)).date())
        query.filter('duTru', True)
        dh = query.get()
        if dh is None:
            dh = DonHang()
            dh.maNVDat = maNV
            #dh.maKH = maNV
            dh.ngayDat = (dt.now() + datetime.timedelta(hours=7)).date()
            dh.tenNVDat = NhanVien.get_by_id(maNV).tenNV
            dh.trangThai = TrangThaiDonHang.DA_DAT_HANG
            dh.tongTien = 0.0
            dh.tienDaThanhToan = 0.0
            dh.duTru = True
            dh.save()
        return dh.key().id()
        
    
    def donHangMau(self):
        maDHMau = self.request.get('maDHMau')
        maDH = self.request.get('maDH')
        
        #xoa het thong tin maDH
        dhMau = DonHang.get_by_id(int(maDHMau))
        dh = DonHang.get_by_id(int(maDH))
        dh.ngayDat = (dt.now() + datetime.timedelta(hours=7)).date()
        dh.ngayGiao = dhMau.ngayGiao
        dh.ngayGiao1 = dhMau.ngayGiao1
        dh.maKH = dhMau.maKH
        dh.ngayThanhToan = dhMau.ngayThanhToan
        dh.ghiChu = dhMau.ghiChu
        dh.tongTien = dhMau.tongTien
        
        lstPut = []
        lstPut.append(dh)
        
        lstCtdh = ChiTietDonHang.all().filter('maDonHang =', dh.key().id()).run()
        db.delete(lstCtdh)
        
        lstCtdhMau = ChiTietDonHang.all().filter('maDonHang =', dhMau.key().id()).run()
        for item in lstCtdhMau:
            ctdh = ChiTietDonHang()
            ctdh.maHang = item.maHang
            ctdh.tenHang = item.tenHang
            ctdh.soLuong = item.soLuong
            ctdh.duTru = item.duTru
            ctdh.donGia = item.donGia
            ctdh.thanhTien = item.thanhTien
            ctdh.ghiChu = item.ghiChu
            ctdh.trangThai = TrangThaiGiaBan.DUYET
            ctdh.maDonHang = int(maDH)
            lstPut.append(ctdh)
        
        db.put(lstPut)
        
        return maDH
        
        